#pragma once

#include "CTableConfigure.h"
#include "CLogDatabase.h"
#include "CLogBatch.h"

#include "CUploadBatch.h"

class CTableBase
{
public:
	CTableBase();
	virtual int	 getTableType() const;
	virtual std::string getTableName() const;
	virtual void setTableConfigure(const CTableConfigurePtr& tableConfigure);
	CTableConfigurePtr getTableConfigure() const ;
	
	virtual void setLogDatabase(const CLogDatabasePtr& logDatabase);
	CLogDatabasePtr getLogDatabase() const;
	virtual const std::map<std::string, CTableField>& getTableFields() const;

	virtual int InitTable();

	virtual int getLevel();

	virtual int writeLog(CLogBatchPtr logBatch);
	virtual int writeRecord(CLogRecordPtr logRecord);

	// 写日志前调用，用于给默认字段赋值
	virtual int beforeWriteLog( CLogBatchPtr logBatch );

	virtual int beforeWriteRecord(CLogRecordPtr logRecord);

	virtual int getUploadBatch(CUpLoadBatchPtr uploadBatch);
	virtual int batchUploadSuccess(CUpLoadBatchPtr uploadBatch);

	virtual int getUploadFailedCount();
	
	virtual void setUploadFailedCount(int nFailedCount);
	virtual bool canUpload();

	uint64_t getUploadedCursor();
	
	// 手动更新上传游标
	int updateUploadCursor(uint64_t newCursor);

	static std::string generateUUID();
	
protected:
	virtual std::string getCreateTableSql();
	virtual std::string getUpdateTableSql();

	uint64_t getTimestamp();
	// 通用的记录插入方法
	virtual int InsertRecord(CLogRecordPtr logRecord);
	// 计算记录大小的辅助方法
	virtual uint64_t calculateRecordSize(CLogRecordPtr logRecord);

private:
	std::vector<CTableField> getTableFieldsBySql();
	int createrTableBySql();
	int updateTableBySql();
	int initUploadCursor();
protected:
	CTableConfigurePtr m_tableConfigure;
	CLogDatabasePtr m_logDatabase; // Pointer to the log database this table belongs to

	std::map<std::string, CTableField> m_tableFields; // Map to hold table fields for fast lookup
	int m_level, m_uploadFailedCount;
	uint64_t m_uploadedCursor;
};

typedef std::shared_ptr<CTableBase> CTableBasePtr;
